# -*- coding: UTF-8 -*-
from lj_tool import tool_url
from . import tool_cache
from minio import Minio
from lj_orm import tool_channel


class LJMinio():
    def __init__(self, minio_endpoint, minio_access_key, minio_secret_key) -> None:
        self.minio_endpoint = minio_endpoint
        self.minio_access_key = minio_access_key
        self.minio_secret_key = minio_secret_key
        # 创建MinIO客户端
        self.minio_client = Minio(
            minio_endpoint, access_key=minio_access_key, secret_key=minio_secret_key,
            secure=False)

    def put_object(self, bucket, name, local_path):
        print(f"{bucket} - {name, local_path}")
        self.minio_client.fput_object(bucket_name=bucket, object_name=name,
                                      file_path=local_path)
        return self.gen_static_url(bucket, name)

    def gen_url(self, bucket, name, expires=60 * 60 * 24 * 365 * 10):
        # 生成访问url 默认10年
        return self.minio_client.presigned_get_object(bucket, name)

    def gen_static_url(self, bucket, name):
        return f"http://{self.minio_endpoint}/{bucket}/{name}"


@tool_cache.lj_wrapper_cache(key="tool_minio_init_default", expiration_seconds=60 * 60 * 8)
def init_default():
    channel = tool_channel.get_channel("402809817fbc4f3d017fbcbed26a001d")
    return LJMinio(tool_url.remvoe_protocol(channel.endpoint), channel.app_key, channel.app_secret)
